package insight.springia5.chapter08.amqp.producer;

import insight.springia5.chapter06.domain.Order;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 与 JMS 类似, 也是有3种方法
 * 不同的是需要 Exchange & Routing Key
 * 
 * @author insight
 * @since 2021/7/22
 */
@Service
public class OrderMsgProducerImpl implements OrderMsgProducer {
    private RabbitTemplate rabbitTemplate;

    @Autowired
    public OrderMsgProducerImpl(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 从最简单的 send() 开始
     * 不同于 JMS 需要手动编写转换成消息, 可以直接获取转换器
     * 此处使用默认的 exchange & key 两者都为空字符串
     */
    /*@Override
    public void sendOrder(Order order) {
        Message message = rabbitTemplate.getMessageConverter().toMessage(order,
                new MessageProperties());
        rabbitTemplate.send(message);
    }*/

    /**
     * convertAndSend() 无需获取转换器
     * 手动指定 key
     */
    /*@Override
    public void sendOrder(Order order) {
        rabbitTemplate.convertAndSend("tacocloud.orders", order);
    }*/

    /**
     * 类似上一节 需要在订单头部添加来源
     */
    /*@Override
    public void sendOrder(Order order) {
        MessageConverter converter = rabbitTemplate.getMessageConverter();
        MessageProperties prop = new MessageProperties();
        
        prop.setHeader("ORDER_SOURCE", "WEB");
        Message msg = converter.toMessage(order, prop);

        rabbitTemplate.send("tacocloud.orders", msg);
    }*/

    /**
     * convertAndSend() 的做法
     */
    @Override
    public void sendOrder(Order order) {
        rabbitTemplate.convertAndSend("tacocloud.orders", order,
                message -> {
                    MessageProperties prop =
                            message.getMessageProperties();
                    prop.setHeader("ORDER_SOURCE", "WEB");
                    return message;
                }
        );
    }
}